package com.radon.plus;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class RequestTimeFilter implements GatewayFilter, Ordered {

    private static Logger logger = LoggerFactory.getLogger(GatewayFilter.class);
    private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";

    /**
     * 获取执行时间
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(REQUEST_TIME_BEGIN,System.currentTimeMillis());
        return chain.filter(exchange).then(
                Mono.fromRunnable(()->{
                    Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
                    if (startTime!=null){
                        logger.info("请求路径："+exchange.getRequest().getURI().getRawPath()+"消耗时间: "+ (System.currentTimeMillis() - startTime) +"ms");
                    }
                })
        );
    }

    /**
     * Ordered的int getOrder（）方法是来给过滤器定优先级的
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
